/*
    2021-06-03 xia.he
 */
const dateUtil = require("../utils/dateUtil")
const statusCode = require('../utils/status-code');//code返回
const optJson = require("../utils/opt.json")
// noise true表示进入噪点,false表示不进入噪点
let noise = true;

/**
 * 切换是否开启噪点
 * @param ctx
 * @returns {Promise<void>}
 */
function changeStatus(ctx) {
    let {status} = ctx.request.body;
    if (status === true) {
        noise = status;
        ctx.body = statusCode.SUCCESS_200("切换成噪点数据", noise);
    } else if (status === false) {
        noise = status;
        ctx.body = statusCode.SUCCESS_200("切换成非噪点数据", noise);
    } else {
        ctx.body = statusCode.SUCCESS_200("切换失败(传入的值不对)");
    }

}

/**
 * 获取用户平均值
 * delay 延迟
 * loss  丢包
 * jitter抖动
 * @param ctx
 * @returns {Promise<{msg: *, code: number, data: *}>}
 */
async function getTaskAvg(ctx) {
    //开始时间
    let startTime = dateUtil.getOneDay();
    //结束时间
    let endTime = dateUtil.getCurrentDate();

    let {task_id, idc_ip} = ctx.request.body;
    try {
        let sql = "";
        if (noise === true) {
            sql = `select  toDecimal64(SUM(delay)/IF(SUM(if(delay>0, 1, 0))>0,SUM(if(delay>0, 1, 0)),1), 2) delays,AVG(loss) losss,toDecimal64(SUM(jitter)/IF(SUM(if(jitter>0, 1, 0))>0,SUM(if(jitter>0, 1, 0)),1), 2) jitters from idc_initial_dist WHERE report_time>='${startTime}' AND report_time<='${endTime}' AND task_id=${task_id} AND idc_ip='${idc_ip}' AND ( delay <= (SELECT iid.delay FROM idc_initial_dist iid WHERE iid.task_id = ${task_id} ORDER BY iid.delay DESC limit toInt32(( SELECT count(iid.task_id) - 1 FROM idc_initial_dist iid WHERE iid.task_id = ${task_id})* (5)/ 100), 1))`;
        } else {
            sql = `select  toDecimal64(SUM(delay)/IF(SUM(if(delay>0, 1, 0))>0,SUM(if(delay>0, 1, 0)),1), 2) delays,AVG(loss) losss,toDecimal64(SUM(jitter)/IF(SUM(if(jitter>0, 1, 0))>0,SUM(if(jitter>0, 1, 0)),1), 2) jitters from idc_initial_dist WHERE report_time>='${startTime}' AND report_time<='${endTime}' AND task_id=${task_id} AND idc_ip='${idc_ip}' `;
        }
        let rows = await clickhouse.query(sql).toPromise();
        if (rows) {
            return ctx.body = statusCode.SUCCESS_200("查询成功", rows);
        }
        ctx.body = statusCode.SUCCESS_200("查询成功", "");
    } catch (e) {
        console.log('getTaskAvg:%s', e.toString());
        ctx.body = statusCode.ERROR_400(e.toString());
        throw new Error(e);
    }
}

/**
 * 获取线路地图数据
 * @param ctx
 * @returns {Promise<{msg: *, code: number, data: *}>}
 */
async function getTaskMap(ctx) {
    //开始时间
    let startTime = dateUtil.getOneDay();
    //结束时间
    let endTime = dateUtil.getCurrentDate();

    let {task_id, idc_ip} = ctx.request.body;
    try {
        let sql = "";
        if (noise === true) {
            sql = `SELECT province_name,AVG(delay) delays,AVG(loss) losss,AVG(jitter) jitters from idc_initial_dist WHERE report_time >='${startTime}' AND report_time <='${endTime}' AND  task_id=${task_id} AND idc_ip ='${idc_ip}' AND delay > 0 AND ( delay <= (SELECT iid.delay FROM idc_initial_dist iid WHERE iid.task_id = ${task_id} ORDER BY iid.delay DESC limit toInt32(( SELECT count(iid.task_id) - 1 FROM idc_initial_dist iid WHERE iid.task_id = ${task_id})* (5)/ 100), 1)) AND delay > 0 group by province_name`;
        } else {
            sql = `SELECT province_name,AVG(delay) delays,AVG(loss) losss,AVG(jitter) jitters from idc_initial_dist WHERE report_time >='${startTime}' AND report_time <='${endTime}' AND  task_id=${task_id} AND idc_ip ='${idc_ip}' AND delay > 0 group by province_name`;
        }
        let rows = await clickhouse.query(sql).toPromise();
        if (rows) {
            return ctx.body = statusCode.SUCCESS_200("查询成功", rows);
        }
        ctx.body = statusCode.SUCCESS_200("查询成功", "");
    } catch (e) {
        console.log('getTaskMap:%s', e.toString());
        ctx.body = statusCode.ERROR_400(e.toString());
        throw new Error(e);
    }
}


/**
 * 获取top优差
 * @param ctx
 * @returns {Promise<{msg: *, code: number, data: *}>}
 */
async function getBar(ctx) {
    //开始时间
    let startTime = dateUtil.getOneDay();
    //结束时间
    let endTime = dateUtil.getCurrentDate();

    let {task_id, idc_ip} = ctx.request.body;
    try {
        let data = {
            //优
            "excellent": {
                "delays": {},
                "losss": {},
                "jitters": {}
            },
            //差
            "difference": {
                "delays": {},
                "losss": {},
                "jitters": {}
            },
            "type": ""
        };

        let array = ["delay", "loss", "jitter"];
        for (let i = 0; i < array.length; i++) {
            let sql = "";
            if (noise === true) {
                sql = `SELECT province_name ,opt_type,AVG(${array[i]}) avgData from idc_initial_dist WHERE report_time >='${startTime}' AND report_time <='${endTime}' AND  task_id=${task_id} AND idc_ip ='${idc_ip}' AND delay > 0  AND ( delay <= (SELECT iid.delay FROM idc_initial_dist iid WHERE iid.task_id = ${task_id} ORDER BY iid.delay DESC limit toInt32(( SELECT count(iid.task_id) - 1 FROM idc_initial_dist iid WHERE iid.task_id = ${task_id})* (5)/ 100), 1)) AND delay > 0 group by province_name ,opt_type ORDER BY avgData asc`;
            } else {
                sql = `SELECT province_name ,opt_type,AVG(${array[i]}) avgData from idc_initial_dist WHERE report_time >='${startTime}' AND report_time <='${endTime}' AND  task_id=${task_id} AND idc_ip ='${idc_ip}' AND delay > 0 group by province_name ,opt_type ORDER BY avgData asc`;
            }
            if (array[i] === "delay") {
                if (noise === true) {
                    sql = `SELECT province_name ,opt_type,toDecimal64(SUM(delay)/ IF(SUM(if(delay>0, 1, 0))>0,SUM(if(delay>0, 1, 0)),1),2)  avgData from idc_initial_dist WHERE report_time >='${startTime}' AND report_time <='${endTime}' AND  task_id=${task_id} AND idc_ip ='${idc_ip}' AND delay > 0 AND delay > 0  AND ( delay <= (SELECT iid.delay FROM idc_initial_dist iid WHERE iid.task_id = ${task_id} ORDER BY iid.delay DESC limit toInt32(( SELECT count(iid.task_id) - 1 FROM idc_initial_dist iid WHERE iid.task_id = ${task_id})* (5)/ 100), 1)) AND delay > 0 group by province_name ,opt_type ORDER BY avgData asc`;
                } else {
                    sql = `SELECT province_name ,opt_type,toDecimal64(SUM(delay)/ IF(SUM(if(delay>0, 1, 0))>0,SUM(if(delay>0, 1, 0)),1),2)  avgData from idc_initial_dist WHERE report_time >='${startTime}' AND report_time <='${endTime}' AND  task_id=${task_id} AND idc_ip ='${idc_ip}' AND delay > 0 group by province_name ,opt_type ORDER BY avgData asc`;
                }
            } else if (array[i] === "jitter") {
                if (noise === true) {
                    sql = `SELECT province_name ,opt_type,toDecimal64(SUM(jitter)/ IF(SUM(if(jitter>0, 1, 0))>0,SUM(if(jitter>0, 1, 0)), 1), 2) avgData from idc_initial_dist WHERE report_time >='${startTime}' AND report_time <='${endTime}' AND  task_id=${task_id} AND idc_ip ='${idc_ip}' AND delay > 0 AND delay > 0  AND ( delay <= (SELECT iid.delay FROM idc_initial_dist iid WHERE iid.task_id = ${task_id} ORDER BY iid.delay DESC limit toInt32(( SELECT count(iid.task_id) - 1 FROM idc_initial_dist iid WHERE iid.task_id = ${task_id})* (5)/ 100), 1)) AND delay > 0 group by province_name ,opt_type ORDER BY avgData asc`;
                } else {
                    sql = `SELECT province_name ,opt_type,toDecimal64(SUM(jitter)/ IF(SUM(if(jitter>0, 1, 0))>0,SUM(if(jitter>0, 1, 0)), 1), 2) avgData from idc_initial_dist WHERE report_time >='${startTime}' AND report_time <='${endTime}' AND  task_id=${task_id} AND idc_ip ='${idc_ip}' AND delay > 0 group by province_name ,opt_type ORDER BY avgData asc`;
                }
            }
            let rows = await clickhouse.query(sql).toPromise();
            let name = [];
            let value = [];
            let name1 = [];
            let value1 = [];
            //大于10取前五,和后五+
            if (rows && rows.length >= 10) {
                //优
                let A = rows.slice(0, 5);
                A.forEach(r => {
                    name.push(r.province_name + optJson[r.opt_type])
                    value.push((r.avgData).toFixed(2))
                })
                //差
                let B = rows.slice(-5);
                B.sort(function (a, b) {
                    return b.avgData - a.avgData;
                })
                B.forEach(r => {
                    name1.push(r.province_name + optJson[r.opt_type])
                    value1.push((r.avgData).toFixed(2))
                })
                data.type = "2";
            }
            // 判断长度小于10
            if (rows && rows.length < 10) {
                if (rows && rows.length > 0) {
                    rows.forEach(r => {
                        name.push(r.province_name + optJson[r.opt_type])
                        value.push((r.avgData).toFixed(2))
                    })
                    let num = 9 - rows.length;
                    for (let i = 0; i < num; i++) {
                        name.push("")
                        value.push("")
                    }
                }
                data.type = "1";
            }
            // data.type = "1";
            if (array[i] === "delay") {
                data.excellent.delays["name"] = name;
                data.excellent.delays["value"] = value;
                data.difference.delays["name"] = name1;
                data.difference.delays["value"] = value1;
            }
            if (array[i] === "loss") {
                data.excellent.losss["name"] = name;
                data.excellent.losss["value"] = value;
                data.difference.losss["name"] = name1;
                data.difference.losss["value"] = value1;
            }
            if (array[i] === "jitter") {
                data.excellent.jitters["name"] = name;
                data.excellent.jitters["value"] = value;
                data.difference.jitters["name"] = name1;
                data.difference.jitters["value"] = value1;
            }
        }
        ctx.body = statusCode.SUCCESS_200("查询成功", data);
    } catch (e) {
        console.log('getBar:%s', e.toString());
        ctx.body = statusCode.ERROR_400(e.toString());
        throw new Error(e);
    }
}

/**
 * 获取line数据
 * num 监测频率
 * @param ctx
 * @returns {Promise<{msg: *, code: number, data: *}>}
 */
async function getLine(ctx) {
    //开始时间
    let startTime = dateUtil.getOneDay();
    //结束时间
    let endTime = dateUtil.getCurrentDate();

    let {task_id, idc_ip, num} = ctx.request.body;
    try {
        let sql = '';
        if (noise === true) {
            sql = `select toDateTime( cast( ( floor( (toUnixTimestamp(report_time)   )/ 60 / ${num} ) * 60 * ${num} ) AS INT ) ) as grouptime , AVG(delay) delays,AVG(loss) losss,AVG(jitter) jitters FROM idc_initial_dist WHERE report_time >='${startTime}' AND report_time <='${endTime}' AND  task_id=${task_id} AND idc_ip ='${idc_ip}' AND ( delay <= (SELECT iid.delay FROM idc_initial_dist iid WHERE iid.task_id = ${task_id} ORDER BY iid.delay DESC limit toInt32(( SELECT count(iid.task_id) - 1 FROM idc_initial_dist iid WHERE iid.task_id = ${task_id})* (5)/ 100), 1)) GROUP BY grouptime ORDER BY grouptime`;
        } else {
            sql = `select toDateTime( cast( ( floor( (toUnixTimestamp(report_time)   )/ 60 / ${num} ) * 60 * ${num} ) AS INT ) ) as grouptime , AVG(delay) delays,AVG(loss) losss,AVG(jitter) jitters FROM idc_initial_dist WHERE report_time >='${startTime}' AND report_time <='${endTime}' AND  task_id=${task_id} AND idc_ip ='${idc_ip}' GROUP BY grouptime ORDER BY grouptime`;
        }
        let rows = await clickhouse.query(sql).toPromise();
        if (rows) {
            return ctx.body = statusCode.SUCCESS_200("查询成功", rows);
        }
        ctx.body = statusCode.SUCCESS_200("查询成功", "");
    } catch (e) {
        console.log('getLine:%s', e.toString());
        ctx.body = statusCode.ERROR_400(e.toString());
        throw new Error(e);
    }
}

module.exports = {getTaskAvg, getTaskMap, getBar, getLine, changeStatus}